package com.wjs.blog.service.Imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wjs.blog.dao.dos.Archives;
import com.wjs.blog.dao.mapper.ArticleBodyMapper;
import com.wjs.blog.dao.mapper.ArticleMapper;
import com.wjs.blog.dao.mapper.ArticleTagMapper;
import com.wjs.blog.dao.pojo.Article;
import com.wjs.blog.dao.pojo.ArticleBody;
import com.wjs.blog.dao.pojo.ArticleTag;
import com.wjs.blog.dao.pojo.SysUser;
import com.wjs.blog.service.*;
import com.wjs.blog.util.UserThreadLocal;
import com.wjs.blog.vo.ArticleBodyVo;
import com.wjs.blog.vo.ArticleVo;
import com.wjs.blog.vo.Result;
import com.wjs.blog.vo.TagVo;
import com.wjs.blog.vo.parms.ArticleParms;
import com.wjs.blog.vo.parms.PageParms;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImp implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ThreadService threadService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
//    @Override
//    public Result listArticle(PageParms pageParms) {
//        Page<Article> page=new Page<>(pageParms.getPage(),pageParms.getPageSize());
//        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
//        //分类文章
//        if(pageParms.getCategoryId()!=null){
//            queryWrapper.eq(Article::getCategoryId,pageParms.getCategoryId());
//        }
//        //标签文章
//        List<Long> articleIdLisy=new ArrayList<>();
//        if(pageParms.getTagId()!=null){
//            LambdaQueryWrapper<ArticleTag> wrapper=new LambdaQueryWrapper();
//            wrapper.eq(ArticleTag::getTagId,pageParms.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(wrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIdLisy.add(articleTag.getArticleId());
//            }
//        }
//        if(articleIdLisy.size()>0){
//            queryWrapper.in(Article::getId,articleIdLisy);
//        }
//        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        List<Article> records = articlePage.getRecords();
//        List<ArticleVo> articleVoList=copylist(records,true,true);
//        return Result.success(articleVoList);
//    }

    @Override
    public Result listArticle(PageParms pageParms) {
        Page<Article> page = new Page<>(pageParms.getPage(),pageParms.getPageSize());
        IPage<Article> articleIPage = this.articleMapper.listArticle(page,pageParms.getCategoryId(),pageParms.getTagId(),pageParms.getYear(),pageParms.getMonth());
        return Result.success(copylist(articleIPage.getRecords(),true,true));
    }

    @Override
    public Result HotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copylist(articles,false,false));
    }

    @Override
    public Result NewArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copylist(articles,false,false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Override
    public Result findArticleById(long id) {
        Article article = articleMapper.selectById(id);;
//        System.out.println(article);
        ArticleVo articleVo = copy(article, true, true,true,true);
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }

    @Override
    public Result publish(ArticleParms articleParam) {
        SysUser sysUser = UserThreadLocal.get();
        Article article=new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setCreateDate(System.currentTimeMillis());
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        articleMapper.insert(article);
        //tag
        List<TagVo> tags = articleParam.getTags();
        if(tags!=null){
            for (TagVo tag : tags) {
                ArticleTag articleTag=new ArticleTag();
                Long articleId = article.getId();
                articleTag.setTagId(Long.parseLong(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //body
        ArticleBody articleBody=new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String,String> map=new HashMap<>();
        map.put("id",article.getId().toString());
        return Result.success(map);
    }

    private List<ArticleVo> copylist(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        List<ArticleVo> articleVoList=new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }
    private List<ArticleVo> copylist(List<Article> records,boolean isTag,boolean isAuthor) {
        List<ArticleVo> articleVoList=new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleVoList;
    }
    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        ArticleVo articleVo=new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article,articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        if(isTag){
            Long id = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(id));
        }
        if(isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if(isBody){
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyByid(bodyId));
        }
        if(isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryByid(categoryId));

        }
        return articleVo;
    }
        @Autowired
    ArticleBodyMapper articleBodyMapper;
    private ArticleBodyVo findArticleBodyByid(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo=new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
